package net.dreamlu.iot.mqtt.broker.http;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.core.server.http.api.MqttHttpRoute;
import net.dreamlu.iot.mqtt.core.server.http.api.code.ResultCode;
import net.dreamlu.iot.mqtt.core.server.http.api.result.Result;
import net.dreamlu.iot.mqtt.spring.server.MqttServerTemplate;
import net.dreamlu.mica.core.spring.SpringContextUtil;
import net.dreamlu.mica.core.utils.JsonUtil;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.stereotype.Component;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.utils.hutool.StrUtil;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: chenlf
 * @date: 2023/9/5
 * @description: EndpointsHttpApi
 **/
@Component
@Slf4j
public class RestartHttpApi implements MqttHttpRoute, SmartInitializingSingleton {
    private MqttServerTemplate server;

    @Override
    public String path() {
        return "/api/v1/ops";
    }


    @Override
    public HttpResponse invoke(HttpRequest request) {
        String clientId = request.getParam("clientId");
        String ops = request.getParam("ops");
        if (StrUtil.isBlank(clientId)) {
            return Result.fail(request, ResultCode.E101);
        }
        Map<String, String> opsData = new HashMap<>();
        opsData.put("ops", ops);
        //发送指令
        boolean publish = server.publish(clientId, "/v3/ops", JsonUtil.toJson(opsData).getBytes(StandardCharsets.UTF_8));
        log.info("发送指令到clientId:{} :result:{}", clientId, publish);
        return Result.ok(request, publish);
    }

    @Override
    public void afterSingletonsInstantiated() {
        this.server = SpringContextUtil.getBean(MqttServerTemplate.class);
    }
}
